package com.songcha.module_main.ui.fragment.calendar

import android.os.Bundle
import android.view.View
import androidx.compose.runtime.Composable
import com.songcha.library_base.compose.BaseComposeMvvmFragment
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.module_main.databinding.MainFragCalendarBinding
import com.songcha.module_main.R
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.material3.Button
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.TimePickerDialogHelper
import com.songcha.library_calendar.calendarview.Calendar
import com.songcha.library_calendar.calendarview.CalendarView
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.ui.view.compose.ComposeImage
import com.songcha.library_common.util.DateUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_main.event.RefreshGongDeEvent
import com.songcha.module_main.ui.activity.main.MainActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class CalendarFragment : BaseMvvmFragment<CalendarViewModel,MainFragCalendarBinding>(), View.OnClickListener,BottomNavigationView.IOnBottomNavigationItemChangeListener {
    private var mIsCurrentBottomTab = false

    init {
        TAG = CalendarFragment::class.java.simpleName
    }

    override fun getLayoutId(): Int {
        return R.layout.main_frag_calendar
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        databinding.mianLlPreMonth.setOnClickListener(this)
        databinding.mianLlNextMonth.setOnClickListener(this)
        databinding.mainTvCurrentDate.setOnClickListener(this)

        databinding.mainCldv.setCurrentCalendarTime(TimeUtil.getCurrentTime())

        databinding.mainCldv.post {
            viewModel.setCurrentDate(databinding.mainCldv.curYear,databinding.mainCldv.curMonth,databinding.mainCldv.curDay)
            getData()
        }

        /*databinding.mainCldv.setOnYearChangeListener{year->
            viewModel.setCurrentDate(year,viewModel.currentDate.value!![1],viewModel.currentDate.value!![2])
        }

        databinding.mainCldv.setOnMonthChangeListener{year,month->
            viewModel.setCurrentDate(year,month,databinding.mainCldv.curDay)
        }*/

        databinding.mainCldv.setOnCalendarSelectListener(object :
            CalendarView.OnCalendarSelectListener {
            override fun onCalendarOutOfRange(calendar: Calendar) {

            }

            override fun onCalendarSelect(calendar: Calendar, isClick: Boolean) {
                viewModel.setCurrentDate(calendar.year,calendar.month,calendar.day)
                viewModel.getCalendarTaskRecord()
            }

        })

        databinding.mainCpv.setContent {
            TaskView()
        }

        initAdvert()

        EventBus.getDefault().register(this)

    }

    private fun initAdvert(){
        AdvertCoverHelper.loadAdvertByCoverXxl(requireActivity(),VarConfig.ADVERT_CALENDAR_XXL_INFO,
            databinding.mainFlAdvertXxl,28f)

        AdvertCoverHelper.loadAdvertByCoverBanner(requireActivity(),VarConfig.ADVERT_CALENDAR_BANNER_INFO,
            databinding.mainFlAdvertBanner,0f)
    }

    override fun initObserver() {
        viewModel.currentDate.observe(this){data->
            databinding.mainTvCurrentDate.text = "${data[0]}年${data[1]}月"
        }
    }

    @Composable
    private fun TaskView(){
        val currentDate by viewModel.currentDate.observeAsState()
        val curTaskRecordBean by viewModel.curTaskRecordBean.collectAsState()

        if(currentDate == null) return

        val one = if(curTaskRecordBean.one!= null) curTaskRecordBean.one else 0
        val two = if(curTaskRecordBean.two!= null) curTaskRecordBean.two else 0
        val three = if(curTaskRecordBean.three!= null) curTaskRecordBean.three else 0
        val four = if(curTaskRecordBean.four!= null) curTaskRecordBean.four else 0

        var completeCount = 0
        if(one > 0) completeCount++
        if(two > 0) completeCount++
        if(three > 0) completeCount++
        if(four > 0) completeCount++

        @Composable
        fun GongDeItemView(){
            Row (
                modifier = Modifier.fillMaxWidth()
                    .height(72.dp),
                verticalAlignment = Alignment.CenterVertically
            ){

                ComposeImage(
                    modifier = Modifier.padding(start = 10.dp)
                        .size(36.dp),
                    id = R.mipmap.main_icon_calendar_task_jrgd
                )

                Text(
                    modifier = Modifier.padding(start = 12.dp),
                    text = "今日功德", fontSize = 13.sp,color = Color(0xffDCAB89), fontWeight = FontWeight.Bold)

                Spacer(modifier = Modifier.weight(1f))

                Text(
                    modifier = Modifier.padding(end = 15.dp),
                    text = "${one} 功德", fontSize = 13.sp,color = Color(0xffDCAB89), fontWeight = FontWeight.Bold)

            }
        }

        @Composable
        fun LineView(){
            Box(
                modifier = Modifier.padding(10.dp,0.dp)
                    .fillMaxWidth()
                    .height(0.5.dp)
                    .background(Color(0x33DCAB89))
            )
        }

        @Composable
        fun ItemView(title:String,resId:Int,isLike:Boolean,onClick:()->Unit){
            Row (
                modifier = Modifier.fillMaxWidth()
                    .height(72.dp),
                verticalAlignment = Alignment.CenterVertically
            ){

                ComposeImage(
                    modifier = Modifier.padding(start = 10.dp)
                        .size(36.dp),
                    id = resId
                )

                Text(
                    modifier = Modifier.padding(start = 12.dp),
                    text = title, fontSize = 13.sp,color = Color(0xffDCAB89), fontWeight = FontWeight.Bold)

                Spacer(modifier = Modifier.weight(1f))

                ComposeImage(
                    modifier = Modifier.padding(end = 34.dp)
                        .size(26.dp)
                        .clickable {
                            onClick()
                        },
                    id = if(isLike) R.mipmap.main_icon_calendar_task_like else R.mipmap.main_icon_calendar_task_unlike
                )

            }
        }

        Box(
            modifier = Modifier.padding(14.dp,0.dp)
                .fillMaxWidth()
                .height(330.dp)
        ){
            ComposeImage(
                modifier = Modifier.fillMaxSize(),
                id = R.mipmap.main_bg_calendar_task
            )

            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth()
                        .height(42.dp),
                    verticalAlignment = Alignment.CenterVertically
                ){
                    ComposeImage(
                        modifier = Modifier.padding(start = 14.dp)
                            .size(16.dp,19.dp),
                        id = R.mipmap.main_icon_calendar_note
                    )

                    Text(
                        modifier = Modifier.padding(start = 7.dp),
                        text = "${currentDate!![0]}-${String.format("%02d",currentDate!![1])}-${String.format("%02d",currentDate!![2])}的记录",
                        fontSize = 12.sp,
                        color = Color(0xffFFCCA9))

                    Spacer(modifier = Modifier.weight(1f))

                    Text(
                        modifier = Modifier.padding(end = 15.dp),
                        text = "已完成(${completeCount}/4)", fontSize = 12.sp,color = Color(0x7fFFCCA9))
                }

                GongDeItemView()

                LineView()

                ItemView("日行一善",R.mipmap.main_icon_calendar_task_rxys,two == 1){
                    if(two == 1) return@ItemView
                    val diff = viewModel.diffCurrentDateToday()
                    if(diff < 0){
                        ToastUtil.show("亲，这一天已经过去了")
                    }else if(diff > 0){
                        ToastUtil.show("亲，还没到当前日期哦")
                    }else{
                        viewModel.updateCalendarTaskRecord(2)
                    }
                }

                LineView()

                ItemView("三省吾身",R.mipmap.main_icon_calendar_task_ssws,three == 1){
                    if(three == 1) return@ItemView
                    val diff = viewModel.diffCurrentDateToday()
                    if(diff < 0){
                        ToastUtil.show("亲，这一天已经过去了")
                    }else if(diff > 0){
                        ToastUtil.show("亲，还没到当前日期哦")
                    }else{
                        viewModel.updateCalendarTaskRecord(3)
                    }
                }

                LineView()

                ItemView("强身健体",R.mipmap.main_icon_calendar_task_qsjt,four == 1){
                    if(four == 1) return@ItemView
                    val diff = viewModel.diffCurrentDateToday()
                    if(diff < 0){
                        ToastUtil.show("亲，这一天已经过去了")
                    }else if(diff > 0){
                        ToastUtil.show("亲，还没到当前日期哦")
                    }else{
                        viewModel.updateCalendarTaskRecord(4)
                    }
                }

            }

        }
    }

    private fun scrollToCalendarByMonth(month:Int){
        val calendar = DateUtil.calendarAddMonth(DateUtil.yearMonthDay2Calendar(viewModel.currentDate.value!![0],viewModel.currentDate.value!![1],viewModel.currentDate.value!![2]),month)
        databinding.mainCldv.scrollToCalendar(DateUtil.getYear(calendar),DateUtil.getMonth(calendar),DateUtil.getDay(calendar))
    }

    override fun onClick(v: View) {
        when(v.id){
            R.id.mian_ll_pre_month->{
                scrollToCalendarByMonth(-1)
            }
            R.id.mian_ll_next_month->{
                scrollToCalendarByMonth(1)
            }
            R.id.main_tv_current_date->{
                val arr = viewModel.currentDate.value!!
                TimePickerDialogHelper.showTimePickerDialog(v.context,false,DateUtil.yearMonthDay2Calendar(arr[0],arr[1],arr[2]),null,
                    2099,
                    null,false,false,false,null,false,
                    android.graphics.Color.parseColor("#1A1A1A"))
                { ts, year, month, day, h, m, s, isLunar->
                    databinding.mainCldv.scrollToCalendar(year,month,day)
                }
            }
        }
    }

    private fun getData(){
        viewModel.getTodayGongDe{
            viewModel.getCalendarTaskRecord()
        }
    }

    @Subscribe
    fun onRefreshGongDe(event:RefreshGongDeEvent){
        if(!mIsCurrentBottomTab) return
        getData()
    }

    override fun onBottomNavigationItemChange(position: Int, tag: String) {
        if(tag == TAG){
            mIsCurrentBottomTab = true
            getData()
        }else{
            mIsCurrentBottomTab = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}